package com.ruoyan.controller;

import com.ruoyan.pojo.Books;
import com.ruoyan.service.BooksService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.ruoyan.controller
 * @ClassName: BooksController
 * @Author: ruoyan1998
 * @CreateTime: 2021/5/5 16:00
 * @Description:
 */
@Controller
@RequestMapping("/book")
public class BooksController
{
    @Resource
    private BooksService booksService;

    /**
     * 查询所有的书籍*/
    @RequestMapping("/allbook")
    public String queryAllBook(Model model)
    {
        List<Books> bookList = booksService.queryBooks();

        model.addAttribute("bookList",bookList);

        return "allbook";
    }

    /**
     * 跳转到增加页面*/
    @RequestMapping("/toAddBook")
    public String toAddBook()
    {
        return "toAddBook";
    }

    /**
     * 新增书籍*/
    @RequestMapping("/addBook")
    public String addBook(Books books)
    {
        booksService.addBooks(books);

        return "redirect:/book/allbook";
    }

    /**
     * 跳转到更改信息页面*/
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id, Model model)
    {
        Books books = booksService.queryBooksByID(id);
        model.addAttribute("book",books);
        return "toUpdateBook";
    }

    /**
     * 更新书籍信息*/
    @RequestMapping("/updateBook")
    public String updateBook(Books books)
    {
        booksService.updateBooks(books);

        return "redirect:/book/allbook";
    }

    /**
     * 删除书籍*/
    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id)
    {
        booksService.deleteBooks(id);

        return "redirect:/book/allbook";
    }

    /**
     * 根据书名查询书籍*/
    @RequestMapping("/queryBook")
    public String queryBookByName(String queryBookName,Model model)
    {
        Books books = booksService.queryBookByName(queryBookName.trim());

        List<Books> bookList;

        if(books == null)
        {
            bookList = booksService.queryBooks();
            model.addAttribute("msg","没有找到这本书");
        }
        else
        {
            bookList = new ArrayList<Books>();
            bookList.add(books);
        }

        model.addAttribute("bookList",bookList);

        return "allbook";
    }
}
